import random
import shutil
from django.http import StreamingHttpResponse
from django.views import View
from django.views.decorators.http import require_GET, require_http_methods
from django.views.decorators.csrf import csrf_exempt
import os
from .utils import zip_dir, log_extract, trace_extract
from uniforms.response import Response
from database import log_conn, metric_conn, trace_conn


"""
----------Log View----------
"""


@csrf_exempt
@require_GET
def query_log_data(request):
    try:
        # raise Exception("An error occurred")
        node = request.GET.get("node")
        pod = request.GET.get("pod")
        start_time = request.GET.get("start_time")
        end_time = request.GET.get("end_time")
        data = log_conn.query(
            node=node, pod=pod, start_time=start_time, end_time=end_time
        )
        return Response.success(data=data)
    except Exception as e:
        print(e)
        return Response.server_error()


@csrf_exempt
@require_GET
def extract_log(request):
    start_time = int(request.GET.get("start_time"))
    end_time = int(request.GET.get("end_time"))
    random_number = random.randint(1, 100000000)
    path = f"./temp/log_data/{random_number}"
    log_extract(log_conn, start_time, end_time, path + "/log")
    zip_dir(path)
    shutil.rmtree(path)
    file_path = f"{path}.zip"
    file_name = os.path.basename(file_path)

    def file_iterator(file_path, chunk_size=512):
        with open(file_path, "rb") as f:
            while True:
                data = f.read(chunk_size)
                if not data:
                    break
                yield data
        os.remove(file_path)

    response = StreamingHttpResponse(file_iterator(file_path))
    response["Content-Disposition"] = 'attachment; filename="{0}"'.format(file_name)
    response["Content-Type"] = "application/zip"
    return response

@csrf_exempt
@require_GET
def query_log_num(request):
    try:
        data = log_conn.get_log_number_by_day()
        return Response.success(data=data)
    except Exception as e:
        print(e)
        return Response.server_error()


"""
----------Metric View----------
"""


@csrf_exempt
@require_GET
def query_prometheus_data(request):
    try:
        pod = request.GET.get("pod")
        metric_name = request.GET.get("metric_name")
        start_time = request.GET.get("start_time")
        end_time = request.GET.get("end_time")
        # metric_name = "container_cpu_usage_seconds_total"
        # pod = "checkoutservice"
        # start_time = 1715780131
        # end_time = 1715780433
        data = metric_conn.query_range(
            metric_name, pod, start_time=start_time, end_time=end_time
        )
        # data = metric_conn.get_query_data(start_time, end_time)

        if "error" in data:
            return Response.server_error()
        else:
            # 根据需要格式化或转换data值
            return Response.success(data=data)
    except Exception as e:
        print(e)
        return Response.server_error()


@csrf_exempt
@require_GET
def export_metric_data(request):
    start_time = int(request.GET.get("start_time"))
    end_time = int(request.GET.get("end_time"))
    random_number = random.randint(1, 100000000)

    path = f"./temp/metric_data/{random_number}"
    random_number = metric_conn.export_all_metrics(
        start_time, end_time, path + "/metric"
    )
    zip_dir(path)
    shutil.rmtree(path)

    file_path = f"{path}.zip"
    file_name = os.path.basename(file_path)

    def file_iterator(file_path, chunk_size=512):
        with open(file_path, "rb") as f:
            while True:
                data = f.read(chunk_size)
                if not data:
                    break
                yield data
        os.remove(file_path)

    response = StreamingHttpResponse(file_iterator(file_path))
    response["Content-Disposition"] = 'attachment; filename="{0}"'.format(file_name)
    response["Content-Type"] = "application/zip"
    return response


@csrf_exempt
@require_GET
def query_metric_name(request):
    metric_names = metric_conn.all_metrics()
    return Response.success(data=metric_names)


"""
----------Trace View----------
"""

@csrf_exempt
@require_GET
def query_trace_data(request):
    try:
        # raise Exception("An error occurred")
        start_time = request.GET.get("start_time")
        end_time = request.GET.get("end_time")
        print("start_time: ", start_time)
        data = trace_conn.query(start_time=start_time, end_time=end_time)
        return Response.success(data=data)
    except Exception as e:
        print(e)
        return Response.server_error()


@csrf_exempt
@require_GET
def query_trace_byId(request):
    try:
        # raise Exception("An error occurred")
        trace_id = request.GET.get("trace_id")
        data = trace_conn.trace_byId(trace_id=trace_id)
        return Response.success(data=data)
    except Exception as e:
        print(e)
        return Response.server_error()


@csrf_exempt
@require_GET
def extract_trace(request):
    start_time = int(request.GET.get("start_time"))
    end_time = int(request.GET.get("end_time"))
    random_number = random.randint(1, 100000000)

    path = f"./temp/trace_data/{random_number}"
    trace_extract(trace_conn, start_time, end_time, path + "/trace")
    zip_dir(path)
    shutil.rmtree(path)
    file_path = f"{path}.zip"
    file_name = os.path.basename(file_path)

    def file_iterator(file_path, chunk_size=512):
        with open(file_path, "rb") as f:
            while True:
                data = f.read(chunk_size)
                if not data:
                    break
                yield data
        os.remove(file_path)

    response = StreamingHttpResponse(file_iterator(file_path))
    response["Content-Disposition"] = 'attachment; filename="{0}"'.format(file_name)
    response["Content-Type"] = "application/zip"
    return response
